var popup_time;
var popup_elem = 0;
var popup_show_timer = 0 ;
var popup_reset_timer = 0 ;

$(function() {
  popup_reset();

  $(".views-popup").appendTo("body");
});

Drupal.behaviors.viewsPopup = function(context) {
  $(".views-popup-row").mouseover(function() {
      popup_show(this);
    })
    .mouseout(function() {
      popup_hide(this);
    })
    .mousemove(function(e) {
      popup_move(this,e);
    });
}

function popup_move(me,evt){
  var e, top, left;

  if (Drupal.settings.views_popup.follow_mouse){
    left = evt.pageX + 15;
    top = evt.pageY;

    $("#views-popup-" + $(me).attr("id")).css({
      left: left + 'px',
      top: top + 'px'
    });
  }
}


function popup_show(me) {
  var p, e, top, left, pos ;

  var x = $(me).attr("id");

  e = $("#views-popup-" + $(me).attr("id"));
  if (e == popup_elem) {
    return ; // already handled
  }

  if (! Drupal.settings.views_popup.follow_mouse){
    pos  = $(me).offset();
    left = 20 + pos.left - $(document).scrollLeft();
    top  =  2 + pos.top + $(me).outerHeight() - $(document).scrollTop();
    $(e).css({
      left: left + 'px',
      top:  top  + 'px',
    });
  }

  popup_clear_show_timer();

  if (popup_elem) {
    popup_elem.hide();
    popup_time = 0 ;
  }
  popup_elem = e;
  if ( popup_time == 0 ) {
    popup_show_now();
  } else {
    popup_show_timer = setTimeout("popup_show_now();",popup_time);
  }
}


function popup_show_now() {
  popup_show_timer = 0 ;

  if(popup_elem) {
    popup_elem.show();
    popup_time = 0;
    clearTimeout(popup_reset_timer);
  }
}

function popup_clear_show_timer(){
  if (popup_show_timer) {
    clearTimeout(popup_show_timer);
    popup_show_timer = 0;
  }
}

function popup_hide(me) {
  popup_clear_show_timer();
  clearTimeout(popup_reset_timer);

  $("#views-popup-" + $(me).attr("id")).hide();
  popup_elem = 0;
/*
  if(popup_elem) {
    popup_elem.hide();
    popup_elem = 0;
  }
*/

  popup_reset_timer = setTimeout('popup_reset()',Drupal.settings.views_popup.reset_time);
}

function popup_reset(){
  popup_time = Drupal.settings.views_popup.popup_delay;
}


